package com.yinuo.controller;

import com.alibaba.fastjson.JSON;
import com.yinuo.common.*;
import com.yinuo.entity.GlobalContext;
import com.yinuo.entity.ServiceManage;
import com.yinuo.repository.ServiceManageRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.xml.ws.Service;
import java.io.File;
import java.util.*;

/**
 * Created by gt.ao on 2018/9/25.
 */
@RestController
@RequestMapping("service")
public class ServiceController {
    private static Logger logger = LoggerFactory.getLogger(ServiceController.class);

    @Autowired
    private ServiceManageRepository serviceManageRepository;

    @RequestMapping("serviceAll")
    public String findAll(){
        List<ServiceManage> list =  serviceManageRepository.findAll();
        Map<String,List<ServiceManage>> result = new HashMap<>(20);
        result.put("serviceList",list);
        return JSON.toJSONString(result);
    }

    @RequestMapping("serviceAdd")
    public String serviceAdd(ServiceManage serviceManage){
        if(!StringUtils.isEmpty(serviceManage.getId())){
            return updateService(serviceManage);
        }
        File image = new File(serviceManage.getService_img());
        File service = new File(serviceManage.getService_position());
        if(!image.exists()){
            return JsonResult.toFaild("服务图标没有找到，请确认图标路径是否正确！");
        }
        if(!service.exists()){
            return JsonResult.toFaild("服务没有找到，请确认服务路径是否正确！");
        }
        String filePath = SystemWaiter.getFilesRootPath();
        String relative = GlobalContext.SERVICE_PATH+image.getName();
        FileUtil.fileChannelCopy(image,new File(filePath+relative));
        image.delete();//删除文件
        serviceManage.setId(UUIDUtil.UUID32());
        serviceManage.setService_img("/serviceImages/"+image.getName());
        serviceManage.setIntime(DateUtil.getFullDate());
        serviceManageRepository.save(serviceManage);
        return JsonResult.toSuccess("服务添加成功！");
    }

    private String updateService(ServiceManage serviceManage){
        File image = new File(serviceManage.getService_img());
        File service = new File(serviceManage.getService_position());
        boolean needUpdate = !serviceManage.getService_img().contains("serviceImages");
        if(needUpdate&&!image.exists()){
            return JsonResult.toFaild("服务图标没有找到，请确认图标路径是否正确！");
        }
        if(!service.exists()){
            return JsonResult.toFaild("服务没有找到，请确认服务路径是否正确！");
        }
        if(needUpdate){
            String filePath = SystemWaiter.getFilesRootPath();
            String relative = GlobalContext.SERVICE_PATH+image.getName();
            FileUtil.fileChannelCopy(image,new File(filePath+relative));
            image.delete();//删除文件
            Optional<ServiceManage> optional = serviceManageRepository.findById(serviceManage.getId());
            ServiceManage old = optional.get();
            String oldName = old.getService_img().substring(old.getService_img().lastIndexOf("/"));
            FileUtil.deleteFile(filePath+GlobalContext.SERVICE_PATH+oldName);
            serviceManage.setService_img("/serviceImages/"+image.getName());
        }
        serviceManage.setIntime(DateUtil.getFullDate());
        serviceManageRepository.saveAndFlush(serviceManage);
        return JsonResult.toSuccess("服务修改成功！");
    }

    @RequestMapping("serviceExecute")
    public String execute(String cmdPath,String openModal){
        List<String> list = new ArrayList<>(10);
        if("0".equals(openModal)){
            list.add(SystemWaiter.getFilesRootPath()+cmdPath);
        }else{
            list.add(cmdPath);
        }
        LocalCommand.execCmd(list);
        return JsonResult.toSuccess();
    }

    @RequestMapping("serviceDel")
    public String serviceDel(ServiceManage serviceManage){
        new File(SystemWaiter.getFilesRootPath() + GlobalContext.SERVICE_PATH + serviceManage.getService_img().substring(serviceManage.getService_img().lastIndexOf("/"))).delete();
        serviceManageRepository.delete(serviceManage);
        return JsonResult.toSuccess();
    }

}
